<?php

namespace iBrand\Component\Purchase\Models;

use iBrand\Shop\Backend\Model\Shop;
use iBrand\Shop\Core\Models\Clerk;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

class Transfer extends Model implements Transformable
{
    use SoftDeletes, TransformableTrait;

    const TYPE_OUT = 'transfer_out';  //调出
    const TYPE_IN = 'transfer_in';   //调入

    protected $guarded = ['id'];

    protected $appends = ['out_shop_name', 'in_shop_name'];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $prefix = config('ibrand.app.database.prefix', 'ibrand_');

        $this->setTable($prefix . 'store_transfer');
    }

    public function items()
    {
        return $this->hasMany(TransferItem::class, 'transfer_id');
    }

    public function clerk()
    {
        return $this->belongsTo(Clerk::class, 'clerk_id')->withDefault();
    }

    public function getOutShopNameAttribute()
    {
        if ($this->out_shop_id) {
            $shop = Shop::where('is_enable', 1)->where('id', $this->out_shop_id)->first();
            if ($shop) {
                return $shop->name;
            }
            return '';
        }
        return '其他门店';
    }

    public function getInShopNameAttribute()
    {
        $shop = Shop::where('is_enable', 1)->where('id', $this->in_shop_id)->first();
        if ($shop) {
            return $shop->name;
        }

        return '';
    }
}